package com.yrot.admin.controller;

import com.yrot.admin.entity.SysExpert;
import com.yrot.common.annotation.SysLog;
import com.yrot.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;

/**
 * Created by hemin on 2019/4/12.
 */
@RestController
@Slf4j
public class LoginController {

    @PostMapping("/login")
    public R login(@RequestParam("username") String username,
                   @RequestParam("password") String password,
                   @RequestParam(value = "remember",required = false) String remember,
                   HttpSession session){
        boolean flag = false;
        if(StringUtils.isNotEmpty(remember) && remember.equals("on")){
            flag = true;
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,flag);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysExpert user = (SysExpert) subject.getPrincipal();
            return R.ok(user.getRoleName());
        }catch (Exception e){
            log.error("登录失败",e.getClass().getName());
            return R.error("用户名或密码错误");
        }
    }

    @GetMapping(value="/logout")
    public ModelAndView logout(ModelAndView modelAndView){
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();
        modelAndView.setViewName("/login");
        return modelAndView;
    }

    @GetMapping("/pid")
    public String getPid(){
        String pid = null;
        try {
            FileReader fr = new FileReader("application.pid");
            BufferedReader br = new BufferedReader(fr);
            pid = br.readLine();
            return pid;
        }catch (Exception e){
            return "-1";
        }
    }

}
